package com.cqupt.aop;

import com.cqupt.common.WebLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.CodeSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Modifier;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Aspect
public class WebLogAspect {

    @Pointcut("@annotation(com.cqupt.common.WebLog)")
    private void pointcut() {}

    @Before("pointcut() && @annotation(log)")
    public void advice(JoinPoint jp, WebLog log) {
        System.out.println("注解作用的方法名: " + jp.getSignature().getName());

        System.out.println("所在类的简单类名: " + jp.getSignature().getDeclaringType().getSimpleName());

        System.out.println("所在类的完整类名: " + jp.getSignature().getDeclaringType());

        System.out.println("目标方法的声明类型: " + Modifier.toString(jp.getSignature().getModifiers()));

        System.out.println("日志的内容为：" + log.value());

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String username = String.valueOf(request.getSession().getAttribute("username"));
        System.out.println("session内容为：" + username);

        String[] paramNames = ((CodeSignature)jp.getSignature()).getParameterNames();
        Class[] paramTypes = ((CodeSignature)jp.getSignature()).getParameterTypes();
        Object[] paramValues = jp.getArgs();
        for (int i = 0; i < paramNames.length; i++) {
            System.out.println("参数名：" + paramNames[i] + "，参数类型：" + paramTypes[i].toString() + "，参数值：" + paramValues[i]);
        }

        String time = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date());
        System.out.println("当前时间：" + time);
    }
}
